package com.mit.wx.controller;

import com.mit.wx.dto.AdminDto;
import com.mit.wx.entity.Admin;
import com.mit.wx.service.AdminService;
import com.mit.wx.vo.BasicJsonResult;
import com.mit.wx.vo.EasyUIDataGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 2018/10/20 Create by 郭文梁
 * AdminController
 * 管理员操作控制器
 *
 * @author 郭文梁
 * @date 2018/10/20
 */
@RestController
@RequestMapping("/admin")
public class AdminController {
    private final AdminService adminService;

    @Autowired
    public AdminController(AdminService adminService) {
        this.adminService = adminService;
    }

    @GetMapping("/list")
    public EasyUIDataGrid<Admin> list(Integer page, Integer rows) {
        List<Admin> admins = adminService.list(page, rows);
        long count = adminService.getCount();
        return EasyUIDataGrid.of(count, admins);
    }

    @PostMapping("/delete")
    public BasicJsonResult<Void> delete(Integer id) {
        int delete = adminService.delete(id);
        if (delete > 0) {
            return BasicJsonResult.ok("删除成功");
        } else {
            return BasicJsonResult.error(1, "删除失败；result=" + delete);
        }
    }

    @PostMapping("/create")
    public BasicJsonResult<AdminDto> create(AdminDto adminDto) {
        AdminDto result = adminService.create(adminDto);
        return BasicJsonResult.ok(result);
    }


    @GetMapping(value = "/bind-open-id-qrcode")
    public ResponseEntity<byte[]> adminBindOpenId(Integer adminId) {
        byte[] result = adminService.getBindOpenIdQrCode(adminId);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
        } else {
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("Content-Type", "image/png");
            return new ResponseEntity<>(result, httpHeaders, HttpStatus.OK);
        }
    }
}
